package site.liuming.truismcms.web.service;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import site.liuming.truismcms.core.storage.AbstractUploadService;
import site.liuming.truismcms.core.storage.QiNiuStorageConfiguration;
import site.liuming.truismcms.exceptions.ParameterException;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 七牛云图片上传服务
 *
 */
@Service
public class ImgUploadService extends AbstractUploadService {

    private final Logger logger = LogManager.getLogger(ImgUploadService.class);
    /** The upload manager. */
    private UploadManager uploadManager;

    /** The auth. */
    private Auth auth;

    /** The token. */
    private String token;

    public ImgUploadService(QiNiuStorageConfiguration configuration) {
        this.config = configuration;
        // 初始化
        init();
    }

    private void init() {
        this.uploadManager = new UploadManager(new Configuration(Zone.zone2()));
        logger.info("AccessKey: " + this.config.getAccessKey());
        logger.info("SecretKey: " + this.config.getSecretKey());
        this.auth = Auth.create(config.getAccessKey(), config.getSecretKey());
    }

    /**
     * 图片上传操作
     * @param inputStream 文件输入流
     * @param path 文件存储路径
     * @return
     */
    @Override
    public String uploadImg(FileInputStream inputStream, String path) {
        // 每次上传都去获取 token
        this.token = auth.uploadToken(config.getBucketName());
        // reset token expire time
        String deadline = token.split(":")[2];
        logger.info("Deadline: " + deadline);
        try {
            Response response = uploadManager.put(inputStream, path, token, null, null);
            if(!response.isOK()) {
                throw new IOException();
            }
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            String url = config.getDomain() + "/" + putRet.key;
            return url;
        }catch (Exception e) {
            logger.error(e.getMessage());
            throw new ParameterException(6002);
        }
    }
}
